package org.example;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;


/**
 * @description:
 * @author: cxu
 * @date: 2021/9/5 16:14
 */
public class TicketService implements Runnable {
    /**
     * @description: 初始票池
     */
    private int ticketNum = 100;
    /**
     * @description: 可重入排它锁
     */
    private InterProcessMutex interProcessMutex;

    public TicketService() {
        // Zookeeper客户端连接
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 3);
        CuratorFramework client = CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181")
                .sessionTimeoutMs(60 * 1000)
                .connectionTimeoutMs(15 * 1000)
                .retryPolicy(retryPolicy)
                .build();
        client.start();
        this.interProcessMutex = new InterProcessMutex(client, "/lock");
    }

    public void run() {
        try {
            // 模拟一直买票
            while (true) {
                // 获取锁
                interProcessMutex.acquire();
                if(ticketNum > 0){
                    System.out.println(Thread.currentThread() + ":当前票数" + ticketNum);
                    ticketNum--;
                }
                // 释放锁
                interProcessMutex.release();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 执行买票
    public static void main(String[] args) {
        TicketService ticketService = new TicketService();
        Thread thread1 = new Thread(ticketService, "携程");
        Thread thread2 = new Thread(ticketService, "飞猪");
        thread1.start();
        thread2.start();
    }
}
